package cn.touna.jss.modules.third.zcx;

import cn.touna.risk.api.enums.SystemErrorCodeEnum;
import cn.touna.jss.common.factory.ResponseFactory;
import cn.touna.jss.common.properties.disconf.ZhongchengxinProperties;
import cn.touna.jss.common.util.HttpUtil;
import cn.touna.jss.common.util.ValidUtil;
import cn.touna.jss.modules.adapter.ApiMapping;
import cn.touna.jss.modules.third.zcx.entity.TrareportRequest;
import cn.touna.risk.api.domain.Response;
import com.alibaba.fastjson.JSONObject;
import com.touna.loan.log.service.TracerContextUtil;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.TreeMap;

@Service
public class ZhongchengxinService {

    private static final Logger logger = LogManager.getLogger();

    @Autowired
    private ZhongchengxinProperties config;

    /**
     * 证件类型： 1 为身份证 ,6 为护照
     （默认为身份证）
     */
    private static final String cidType = "1";

    @ApiMapping(value = "zhongchengxin.trareport",desc = "中诚信.获取航空出行数据")
    public Response trareport(TrareportRequest request){
        Response response = ValidUtil.valid(request);
        if(response != null)
            return response;
        Map<String,String> params = new TreeMap<>();
        params.put("account",config.getAccount());
        params.put("name",request.getName());
        params.put("cid",request.getIdCard());
        params.put("reqTid", TracerContextUtil.getTraceId());
        StringBuilder sb = new StringBuilder();

        for (Map.Entry<String, String> entry : params.entrySet()) {
            sb.append(entry.getKey()).append(entry.getValue());
        }
        sb.append(config.getPrivateKey());
        String sign = DigestUtils.md5Hex(sb.toString()).toUpperCase();
        params.put("cidType",cidType);
        params.put("month",request.getMonth());
        params.put("sign",sign);

        try {
            String res = HttpUtil.get(config.getTrareportUrl(),params);
            JSONObject resObj = JSONObject.parseObject(res);
            String resCode = resObj.getString("resCode");
            if("0000".equals(resCode)){
                return ResponseFactory.success(resObj);
            }else{
                String resMsg = resObj.getString("resMsg");
                return ResponseFactory.fail(SystemErrorCodeEnum.JSS_EXTSYSTEM_RESP_ERROR,resCode + ":"+resMsg,resObj);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            return ResponseFactory.fail(SystemErrorCodeEnum.JSS_CALL_EXTSYSTEM_ERROR,e.getMessage());
        }
    }
}
